// listing 1
// Reading a Data File with Regular Expressions.

/* 
each line in the names.txt file is expected to be in this format
	"firstname", "lastname", salary
for example
	"John", "Smith", 40000
	"Ann", "Douglas", 45000
*/
	



using System;
using System.IO;
using System.Text.RegularExpressions;

class Application
{
	static void Main(string[] args)
	{
		// read the data file 
		StreamReader sr = new 
			StreamReader(@"c:\names.txt");
		string text = sr.ReadToEnd();
		sr.Close();

		// this is the search pattern
		string pattern = 
			@"^\s*""(?<first>[^""]+)""\s*," +
			"\s*""(?<last>[^""]+)""\s*," +
			"\s*(?<salary>\d+(\.\d\d)?)\s*$";
		Regex re = new Regex(pattern, 
			RegexOptions.Multiline);

		// find the first match
		Match m = re.Match(text);
		while (m.Success)
		{
			// show details of this match
			Console.WriteLine("FirstName: {0}, " +
				"LastName: {1}, Salary: {2}", 
				m.Groups["first"].Value, 
				m.Groups["last"].Value, 
				m.Groups["salary"].Value);
			// find next match
			m = m.NextMatch();
	   }
	}
}

// Listing 2
// Doing Simple Math.

using System;
using System.Text.RegularExpressions;

class Application
{
	static void Main(string[] args)
	{
		string text = "x=12+23, y=34-18";
		// replace all sums and subtractions with
		// their result
		Regex re = new Regex(@"(\d+)([-+])(\d+)");
		string res = re.Replace(text, _
			new MatchEvaluator(EvalOp));
		Console.WriteLine(res);
	}

	static string EvalOp(Match m)
	{
		// 1st and 3rd groups are the operands
		int op1 = int.Parse(m.Groups[1].Value);
		int op2 = int.Parse(m.Groups[3].Value);
		// 2nd group is the operator
		switch (m.Groups[2].Value)
		{
			case "+": 
				return (op1 + op2).ToString();
			case "-": 
				return (op1 - op2).ToString();
		}
		// the C# compiler requires this
		return null;
	}
}
